package com.example.receiptocr

import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.example.receiptocr.viewModels.LoginState
import com.example.receiptocr.viewModels.LoginViewModel
import androidx.hilt.navigation.compose.hiltViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoginScreen(
    navController: NavController,
    showExpiredDialog: Boolean = false,
    // 使用 hiltViewModel() 获取 LoginViewModel 实例
    loginViewModel: LoginViewModel = hiltViewModel()
) {
    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }

    val loginState by loginViewModel.loginState
    val TAG = "LoginScreen"
    val snackbarHostState = remember { SnackbarHostState() }
    val scope = rememberCoroutineScope()

    // 控制弹窗显示
    var showDialog by remember { mutableStateOf(showExpiredDialog) }
    var dialogMessage by remember { mutableStateOf("") }

    if (showDialog) {
        dialogMessage = "您的会话已过期，请重新登录。"
        AlertDialog(
            onDismissRequest = { showDialog = false },
            confirmButton = {
                TextButton(onClick = { showDialog = false }) {
                    Text("确定")
                }
            },
            text = { Text(dialogMessage) }
        )
    }

    // 监听登录状态变化
    LaunchedEffect(loginState) {
        when (loginState) {
            is LoginState.Success -> {
                // 登录成功后导航到主页面
                navController.navigate("main") {
                    // 防止返回到登录页面
                    popUpTo("login") { inclusive = true }
                }
            }
            is LoginState.Error -> {
                // 显示错误消息通过Snackbar
                val errorMessage = (loginState as LoginState.Error).error
                snackbarHostState.showSnackbar(errorMessage)
                // 重置错误状态，避免重复显示
                loginViewModel.resetState()
            }
            else -> {
                // 处理其他状态（Idle, Loading），不做特殊处理
            }
        }
    }

    // 输入验证逻辑
    val isUsernameValid = username.isNotBlank()
    val isPasswordValid = password.isNotBlank()
    val isFormValid = isUsernameValid && isPasswordValid

    Scaffold(
        snackbarHost = { SnackbarHost(hostState = snackbarHostState) }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize(),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                TextField(
                    value = username,
                    onValueChange = { username = it },
                    label = { Text("Username") },
                    modifier = Modifier.fillMaxWidth(),
                    enabled = loginState !is LoginState.Loading,
                    singleLine = true,
                    isError = !isUsernameValid && username.isNotEmpty()
                )
                if (!isUsernameValid && username.isNotEmpty()) {
                    Text(
                        text = "Username cannot be empty",
                        color = MaterialTheme.colorScheme.error,
                        style = MaterialTheme.typography.bodySmall
                    )
                }
                Spacer(modifier = Modifier.height(8.dp))

                TextField(
                    value = password,
                    onValueChange = { password = it },
                    label = { Text("Password") },
                    visualTransformation = PasswordVisualTransformation(),
                    modifier = Modifier.fillMaxWidth(),
                    enabled = loginState !is LoginState.Loading,
                    singleLine = true,
                    isError = !isPasswordValid && password.isNotEmpty()
                )
                if (!isPasswordValid && password.isNotEmpty()) {
                    Text(
                        text = "Password cannot be empty",
                        color = MaterialTheme.colorScheme.error,
                        style = MaterialTheme.typography.bodySmall
                    )
                }
                Spacer(modifier = Modifier.height(16.dp))

                Button(
                    onClick = {
                        // 触发登录逻辑
                        loginViewModel.login(username, password)
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(50.dp),
                    enabled = isFormValid && loginState !is LoginState.Loading
                ) {
                    if (loginState is LoginState.Loading) {
                        CircularProgressIndicator(
                            color = MaterialTheme.colorScheme.onPrimary,
                            modifier = Modifier.size(24.dp),
                            strokeWidth = 2.dp
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("Logging in...")
                    } else {
                        Text("Login")
                    }
                }

                Spacer(modifier = Modifier.height(8.dp))

                TextButton(
                    onClick = { navController.navigate("register") },
                    enabled = loginState !is LoginState.Loading
                ) {
                    Text("Don't have an account? Register")
                }

                // 显示加载指示器
                if (loginState is LoginState.Loading) {
                    Spacer(modifier = Modifier.height(16.dp))
                    CircularProgressIndicator(modifier = Modifier.align(Alignment.CenterHorizontally))
                }
            }
        }
    }
}
